var gulp = require('gulp'),
    htmlmin = require('gulp-htmlmin'),
    uglify = require('gulp-uglify'),
    copy = require('gulp-copy'),
    pump = require('pump'),
    concat = require('gulp-concat'),
    sourcemaps = require('gulp-sourcemaps'),
    replace = require('gulp-replace'),
    inject = require('gulp-inject'),
    ejs = require('gulp-ejs'),
    gutil = require('gulp-util'),
    useref = require('gulp-useref'),
    gulpif = require('gulp-if'),
    minifyCss = require('gulp-clean-css'),
    rev = require('gulp-rev'),
    imagemin = require('gulp-imagemin'),
    watch = require('gulp-watch'),
    lazypipe = require('lazypipe'),
    fs = require('fs'),
    gulpSequence = require('gulp-sequence'),
    path = require('path'),
    del = require('del'),
    revCollector = require('gulp-rev-collector');
var minifyHTML   = require('gulp-minify-html');
var assetpaths = require('gulp-assetpaths');

var htmlDir = './src/';
var buildDir = './build/';
/**
 * 静态资源路径引用
 */
// gulp.task('change-paths', function(){
//     return gulp.src(['./*.html'])
//         .pipe(assetpaths({
//             newDomain: 'www.thenewdomain.com',
//             oldDomain : 'www.theolddomain.com',
//             docRoot : 'public_html',
//             filetypes : ['jpg','jpeg','png','ico','gif','js','css'],
//             customAttributes: ['data-custom'],
//             templates: true
//         }))
//         .pipe(gulp.dest('../dist'));
// });
gulp.task('copy-css-imge', function () {
    /***
     * 文件监控
     */
    return gulp
        .src([
            'src/libs/**/dist/**/*.png',
            'src/libs/**/skins/square/blue*.png'
        ])
        .pipe(copy('build', {prefix:4}))
    //.dest('build');
});
/**
 * 文件拷贝
 */
gulp.task('copy', function () {
    /***
     * 文件监控
     */
    return gulp
        .src(['src/libs/**/*.eot','src/libs/**/*.svg','src/libs/**/*.ttf','src/libs/**/*.woff'])
        .pipe(copy('build/scripts', {prefix:4}))
        //.dest('build');
});


gulp.task('default', function () {
    /***
     * 文件监控
     */
    watch([htmlDir + '**',], {ignoreInitial: true}, function (event) {
        var path_ = event.path.replace(/\\/g, '/');
        console.log('变动文件-->' + path_);
        if (path_) {
            singleFileTask(path_);
        }
    });
    return readOneLevelFile(htmlDir);
});
gulp.task('dev:step1', function () {
    return readOneLevelFile(htmlDir);
});

/**
 * @date 2017-05-08
 * @desc  handle single file by gulp task
 */
function singleFileTask(path_,isPro) {
    if (path_) {
        //零宽正向先行断言
        var path__ = ['build',path_.replace('src/html/', '').match(/.*(?=\/.*\.html)/)[0]].join('/');
        console.log('处理结果输出路径->' + path__);
        if (path__){
            if(!isPro){
                return gulp.src(path_)
                    .pipe(ejs({
                        root: '',
                        domain:'localhost'
                    }).on('error', gutil.log))
                    .pipe(useref({}, lazypipe().pipe(sourcemaps.init, { loadMaps: true })))
                    // .pipe(rev())
                    .pipe(sourcemaps.write('maps'))
                    .pipe(gulp.dest(path__))
            }else{
                return gulp.src(path_)
                    .pipe(ejs({
                        root: '',
                        domain:'123.57.39.2'
                    }).on('error', gutil.log))
                    .pipe(useref({}))
                    .pipe(gulpif('*.js', uglify()))
                    .pipe(gulpif('*.css', minifyCss()))
                    .pipe(gulp.dest(path__))
            }


        }
    }
}
gulp.task('include-image-libs', function () {
     readOneLevelFile(htmlDir);
    /**
     * 图片处理
     */
    gulp.src('src.test/imgs/**/*.*')    //原图片的位置
        .pipe(imagemin())                   //执行图片压缩
        .pipe(gulp.dest('build/imgs'));
    /**
     * 第三方库脚本库
     */
    gulp.src('src.test/libs/**/*.*')    //原脚本的位置
        .pipe(gulp.dest('build/libs'));
    /**
     * 系统脚本
     */
    gulp.src('src.test/script/**/*.*')    //原脚本的位置
        .pipe(gulp.dest('build/script'));
    /**
     * 样式文件
     */
    gulp.src('src.test/styles/*.*')    //原样式的位置
        .pipe(gulp.dest('build/styles'));
    /**
     * 打包公用js
     */
    return gulp.src('src.test/js/common.js')
        .pipe(gulp.dest('build/js/common.js'));

});
gulp.task('include-without-image-libs', function () {
     readOneLevelFile(htmlDir);
    /**
     * 图片处理
     */
    // gulp.src('src.test/imgs/**/*.*')    //原图片的位置
    //     .pipe(imagemin())                   //执行图片压缩
    //     .pipe(gulp.dest('build/imgs'));
    /**
     * 第三方库脚本库
     */
    // gulp.src('src.test/libs/**/*.*')    //原脚本的位置
    //     .pipe(gulp.dest('build/libs'));
    /**
     * 系统脚本
     */
    gulp.src('src.test/script/**/*.*')    //原脚本的位置
        .pipe(gulp.dest('build/script'));
    /**
     * 样式文件
     */
    gulp.src('src.test/styles/*.*')    //原样式的位置
        .pipe(gulp.dest('build/styles'));
    /**
     * 打包公用js
     */
    return gulp.src('src.test/js/common.js')
        .pipe(gulp.dest('build/js/common.js'));

});
gulp.task('dist:pre-start', function () {
    return del('build/**/*').then(function (paths) {
        console.log('Deleted files and folders:\n', paths.join('\n'));
        })
});

gulp.task('dist:step1', function () {
    readOneLevelFile(htmlDir,true);

    /**
     * 第三方库脚本库
     */
    gulp.src('src.test/libs/**/*.*')    //原脚本的位置
        .pipe(gulp.dest('build/libs'));
    /**
     * 系统脚本
     */
    gulp.src('src.test/script/**/*.*')    //原脚本的位置
        .pipe(gulp.dest('build/script'));
    /**
     * 样式文件
     */
    gulp.src('src.test/styles/*.*')    //原样式的位置
        .pipe(gulp.dest('build/styles'));
    /**
     * 打包公用js
     */
    gulp.src('src.test/js/common.js')
        .pipe(gulp.dest('build/js/common.js'));
    /**
     * 图片处理
     */
    return gulp.src('src.test/imgs/**/*.*')    //原图片的位置
        .pipe(imagemin())                   //执行图片压缩
        .pipe(gulp.dest('build/imgs'));

});
gulp.task('dist:step2:css', function () {
    return gulp.src(['build/**/*.css','!build/libs/**/*.css'])
        .pipe(rev())
        .pipe(gulp.dest('build'))
        .pipe(rev.manifest())
        .pipe(gulp.dest('build/rev/css'))
});
gulp.task('dist:step3:js', function () {
    return gulp.src(['build/**/*.js','build/**/*.js','!build/libs/**/*.js'])
        .pipe(rev())
        .pipe(gulp.dest('build'))
        .pipe(rev.manifest())
        .pipe(gulp.dest('build/rev/js'))
});
gulp.task('dist:step4:rev', function () {
    return gulp.src(['build/rev/**/*.json', 'build/**/*.html'])
        .pipe( revCollector({
            replaceReved: true,
        }))
        .pipe( gulp.dest('build') );
});

gulp.task('dist:step5', function () {
    return gulp.src(['build/**/*.html','!build/libs/**/*.html','!build/common/*.html','!build/script/**/*.html','!build/scripts/**/*.html'])
        .pipe(htmlmin({
            removeComments:true,
            collapseWhitespace: true,
            // ignoreStartTag:/\<\$/,
            // ignoreEndTag:/\$\>/,
            ignoreCustomFragments:[/\<\$[\s\S]*?\$\>/,/\<\$=[\s\S]*?\$\>/,/\<\%\-[\s\S]*?\%\>/],
            ignoreCustomComments: [/^!/],
            minifyJS: true,
            minifyCSS: true
        }))
        .pipe(gulp.dest('build'));

});
gulp.task('sequence-dist', gulpSequence('dist:pre-start','dist:step1',['dist:step2:css', 'dist:step3:js'], 'dist:step4:rev','dist:step5','copy'));
// gulp.task('sequence-dist', gulpSequence('dist:step1','dist:step2:css', 'dist:step3:js', 'dist:step4:rev',  'dist:step5'));
gulp.task('sequence-dev', gulpSequence('dev:step1',['dist:step2:css', 'dist:step3:js'], 'dist:step4:rev'));

/**
 * 最小化
 */
gulp.task('minhtml', function () {
    return gulp.src('build/*.*')
        .pipe(htmlmin({
            collapseWhitespace: true,
            ignoreStartTag:/\<\$/,
            ignoreEndTag:/\$\>/,
            ignoreCustomComments: [/^!/],
//            customAttrSurround:[[/\<\$/,/\$\>/]],
            minifyJS: true, minifyCSS: true
        }))
        .pipe(gulp.dest('build'));
});

/**
 * @author byte_su@163.com
 * @date 2017-05-04 16:00
 * @desc 读取同层级文件处理，判断目录递归处理
 * @param dir_
 * @param isPro true 表示生产环境构建
 */
function readOneLevelFile(dir_,isPro) {
    fs.readdir(dir_, function (err, files) {

        if (err) {
            console.log(err);
        } else {
            files.forEach(function (f) {
                var path_ = (dir_ + f);
                var fd = fs.openSync(path_, 'r');
                var obj_file = fs.fstatSync(fd);
                if (obj_file.isFile() && path.extname(path_).indexOf('.htm') > -1) {
                    if (path_.indexOf('.html') > -1 && path_.indexOf('common') == -1 && path_.indexOf('common') == -1) {
                        // var sources = gulp.src(['./build/common/*.js', './build/common/*.css'], {read: false});
                        console.log('处理文件路径->' + path_)
                        // console.log('[处理结果--]->' + dir_.replace('src.test', 'build').replace('html/', ''))
                        singleFileTask(path_,isPro);
                        // gulp.src(path_)
                        // // .pipe(inject(sources))
                        //
                        //     .pipe(ejs({
                        //         root: '/admin'
                        //     }).on('error', gutil.log))
                        //     .pipe(useref({}))
                        //     // .pipe(gulpif('*.js', uglify()))
                        //     // .pipe(gulpif('*.css', minifyCss()))
                        //     // .pipe(rev())
                        //     .pipe(gulp.dest(dir_.replace('src.test', 'build').replace('html/', '')))
                    } else {
                        console.log('非处理文件->' + path_);
                    }
                } else if (obj_file.isDirectory()) {
                    readOneLevelFile(path_ + '/',isPro);
                } else {
                    console.log('非处理文件->' + path_);
                }
            });
        }
    });
}